import axios from 'axios';
// import Cookies from 'js-cookie';

const request = axios.create({
    baseURL: '',
    timeout: 5000
})
// Add a request interceptor
request.interceptors.request.use(function (config) {
    // Do something before request is sent
    // 前端每次发起接口都要添加一个token
    const token = window.localStorage.getItem('token')
    if (token) {
        config.headers.authorization = "Bearer " + token;
    }
    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

// Add a response interceptor
request.interceptors.response.use(function (response) {
    // Do something with response data
    const res = response.data;
    return res;
}, function (error) {
    // Do something with response error
    switch (error.response.status) {
        case 404:
            //也可以通过路由直接跳转到咱们自己定义的404页面
            alert('接口没有找到')
            break;
        case 403:
            alert('没有权限')
            break;
        case 500:
            alert('服务器内部错误')
            break;
        case 406:
            alert('参数不合法')
            break;
        default:
            break;
    }
    return Promise.reject(error);
});

const http = {
    get(url, data) {
        return request.get(url, {
            params: data
        })
    },
    post(url, data) {
        return request.post(url, data);
    },
    getDetail(url, id) {
        return request.get(url + '/' + id)
    },
};

export default http